package com.snj.visangedu.drm;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import com.snj.visangedu.R;
import com.snj.visangedu.lib.Global;
import com.snj.visangedu.video.StudyVideoView;
import com.teruten.tms4encrypt.TMS4Encrypt;
import com.teruten.tms4webserver.TMS4WebServer;

public class VideoAct extends Activity implements OnClickListener {


	private TMS4WebServer _webServer;
	
	StudyVideoView _video = null;
	VideoView _video_drm = null;
	String TAG = "VideoDRMAct";
	 
	ImageView img_video_guide = null;
	
	ImageView img_video_play = null;
	ImageView img_video_bell = null;
	ImageView img_video_question = null;
	ImageView img_video_x = null;
	
	
	boolean isbell = true;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.video);
		
		_video = (StudyVideoView)findViewById(R.id.video);
		MediaController mc = new MediaController(this);
		//_video.setMediaController(mc);
		
		_video_drm = (VideoView)findViewById(R.id.drm_video);
		
		img_video_guide = (ImageView)findViewById(R.id.img_video_guide);
		
		img_video_play = (ImageView)findViewById(R.id.img_video_play);
		img_video_bell = (ImageView)findViewById(R.id.img_video_bell);
		
		img_video_question = (ImageView)findViewById(R.id.img_video_question);
		img_video_x = (ImageView)findViewById(R.id.img_video_x);
		
		Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.video_guide);
		
		img_video_guide.setImageBitmap(b);
		img_video_guide.setVisibility(View.GONE);
		
		img_video_play.setImageResource(R.drawable.video_pause);
		
		b = BitmapFactory.decodeResource(getResources(), R.drawable.video_bell_on);
		img_video_bell.setImageBitmap(b);
		img_video_question.setImageResource(R.drawable.video_question);
		img_video_x.setImageResource(R.drawable.video_x);
		
		img_video_play.setOnClickListener(this);
		img_video_bell.setOnClickListener(this);
		img_video_question.setOnClickListener(this);
		img_video_x.setOnClickListener(this);
		

		_video.setOnCompletionListener(new OnCompletionListener() {

			public void onCompletion(MediaPlayer mp) {
				Log.e("VideoAct", "completion."); 
				
				_video.start();
			}
		});
		_video.setOnErrorListener(new OnErrorListener() {

			public boolean onError(MediaPlayer mp, int what, int extra) {
				Log.e("VideoAct", "error.");
				return false;
			}
		});
		
		_video_drm.setOnCompletionListener(new OnCompletionListener() {

			public void onCompletion(MediaPlayer mp) {
				Log.e("VideoAct", "completion."); 
				
				_video.start();
			}
		});
		_video_drm.setOnErrorListener(new OnErrorListener() {

			public boolean onError(MediaPlayer mp, int what, int extra) {
				Log.e("VideoAct", "error.");
				return false;
			}
		});
		
		File edumaxfile = new File(Global.ex_storage + "/visangedu/edumax.mp4");
		if(edumaxfile.exists())
		{
			
			Uri video = Uri.parse(Global.ex_storage + "/visangedu/edumax.mp4");
			
			_video.setVideoURI(video);
			_video.start();
		}
		else
		{
			startDownload();
		}
		//Uri video = Uri.parse("http://studyview.co.kr/ms4/edumax.mp4");
		
		edumaxfile = new File(Global.ex_storage + "/visangedu/edumax.mp4");
		if(edumaxfile.exists())
		{
			
			Uri video = Uri.parse(Global.ex_storage + "/visangedu/edumax.mp4");
			
			_video.setVideoURI(video);
			_video.start();
		}
		
		/*
		Intent msgIntent = new Intent();
		msgIntent.setAction("com.snj.visangedu.edumax.bell");
		msgIntent.putExtra("cmd", 1);
		msgIntent.putExtra("bell", "http://studyview.co.kr/ms4/bn.MS4");
		sendBroadcast(msgIntent);
		*/
		//PlayMedia("http://studyview.co.kr/ms4/bn.MS4"); 
	}
	
	//ProgressDialog mDlg = null;
	
	private void startDownload() {
	    String url = "http://studyview.co.kr/ms4/edumax.mp4";
	    new AsyncTask<String, String, String>(){
	    	
	    	@Override
	    	protected void onPreExecute() { 
	    		/*
	    	    mDlg = new ProgressDialog(VideoAct.this);
	    	    mDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	    	    mDlg.setMessage("Initializing EDUMAX...");
	    	    mDlg.show();
	    	 */
	    	    super.onPreExecute();
	    	}

			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				int count = 0;
			     
			    try {
			        Thread.sleep(10);
			        URL url = new URL(params[0].toString());
			        URLConnection conexion = url.openConnection();
			        conexion.connect();
			 
			        int lenghtOfFile = conexion.getContentLength();
			        Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
			 
			        InputStream input = new BufferedInputStream(url.openStream());
			        OutputStream output = new FileOutputStream(Global.ex_storage + "/visangedu/edumax.mp4");
			 
			        byte data[] = new byte[1024];
			 
			        long total = 0;
			 
			        while ((count = input.read(data)) != -1) {
			            total += count;
			            publishProgress("" + (int) ((total * 100) / lenghtOfFile));
			            output.write(data, 0, count);
			        }
			 
			        output.flush();
			        output.close();
			        input.close();
			         
			        // 작업이 진행되면서 호출하며 화면의 업그레이드를 담당하게 된다
			        //publishProgress("progress", 1, "Task " + 1 + " number");
			         
			    } catch (InterruptedException e) {
			        e.printStackTrace();
			    } catch (IOException e) {
			        e.printStackTrace();
			    }
			 
			    // 수행이 끝나고 리턴하는 값은 다음에 수행될 onProgressUpdate 의 파라미터가 된다
			    return null;
			}
			
			@Override
			protected void onProgressUpdate(String... progress) {
				/*
			    if (progress[0].equals("progress")) {
			        mDlg.setProgress(Integer.parseInt(progress[1]));
			        mDlg.setMessage(progress[2]);
			    } else if (progress[0].equals("max")) {
			        mDlg.setMax(Integer.parseInt(progress[1]));
			    }*/
			}
			
			@SuppressWarnings("deprecation")
			@Override
			protected void onPostExecute(String unused) {
			    //mDlg.dismiss();
			    
			    Uri video = Uri.parse(Global.ex_storage + "/visangedu/edumax.mp4");
				
				_video.setVideoURI(video);
				_video.start();
			     
			}
	    	
	    }.execute(url, "1", "1");
	} 
	
	@Override
	protected void onResume() {
		super.onResume();
		//_TMAMCP.resume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		
		Drawable d = img_video_guide.getDrawable();
		if(d instanceof BitmapDrawable)
		{
			Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
			bitmap.recycle();
			bitmap = null;
		}
		d.setCallback(null);
		
		_video.stopPlayback();
		_video = null;
		
		_video_drm.stopPlayback();
		_video_drm = null;
		
		System.gc();
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		Intent msgIntent = new Intent();
		
		switch(v.getId())
		{
		case R.id.img_video_play:
			msgIntent.setAction("com.snj.visangedu.edumax.bell");
			msgIntent.putExtra("cmd", 0);
			
			if(_video.isPlaying())
			{
				_video_drm.pause();
				_video.pause();
				img_video_play.setImageResource(R.drawable.video_play);
			}
			else
			{
				_video_drm.start();
				_video.start();
				img_video_play.setImageResource(R.drawable.video_pause);
			}
			break;
		case R.id.img_video_bell:
			
		
			if(isbell)
			{
				PlayMedia("http://studyview.co.kr/ms4/bf.MS4");
				Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.video_bell_off);
				img_video_bell.setImageBitmap(b);
				isbell = false;
			}
			else
			{
				PlayMedia("http://studyview.co.kr/ms4/bn.MS4");				
				Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.video_bell_on);
				img_video_bell.setImageBitmap(b);
				isbell = true;
			}
			sendBroadcast(msgIntent);
			break;
		case R.id.img_video_question:
			img_video_guide.setVisibility(img_video_guide.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
			break;
		case R.id.img_video_x:
			finish();
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		switch (keyCode) {
	    case KeyEvent.KEYCODE_BACK:
	    	if(img_video_guide.getVisibility() == View.VISIBLE)
	    	{
	    		img_video_guide.setVisibility(View.GONE);
	    		return true;
	    	}
	    	break;
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	public void PlayMedia(String path)
	{
		new AsyncTask<String, String, String>() {

			String strMediaPath1 = "";
			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				
				strMediaPath1 = params[0];
				
				if (strMediaPath1.endsWith(".MS4")) {
					int nReturn;
					
					// 
					DRM_Init();

					// 
					if (strMediaPath1.startsWith("http://")) {
						nReturn = _webServer.OpenRemoteMedia(strMediaPath1);
						if(nReturn != TMS4Encrypt.TMS4E_OK)
						{
							displayMessage("open remote media error : " + nReturn);
							return null;
						}
						else
						{
							Log.d("VideoAct", "Success");
						}
					}
					// 
					else 
					{
						int nTime = (int) (System.currentTimeMillis() / 1000);
						nReturn = _webServer.MediaAccreditation(strMediaPath1, nTime);
						if (nReturn != 0) {
							displayMessage("open local media error : " + nReturn);
							Log.d(TAG, "Faile Accredit : " + Integer.toString(nReturn));
							return null;
						}
						DRM_showInfo();
					}
					
					// DRM 
					strMediaPath1 = _webServer.getFilePath(strMediaPath1);
				}

				
				
				
				
				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				
				//_video.setVideoURI(Uri.parse(strMediaPath));
				if(_video_drm != null)
				{
					_video_drm.setVideoPath(strMediaPath1);
					_video_drm.start();
					Log.e("VideoAct", "media path : " + strMediaPath1);
				}
			}
			
			
			
			
		}.execute(path);
	}
	
	public void StopMedia()
	{
		_video_drm.stopPlayback();
	}
	
	/**********************************************************
	 * DRM
	**********************************************************/
	private void DRM_Init() {
		if (_webServer == null) {
			Log.e(TAG, "web server start");
			_webServer = new TMS4WebServer();
			DRMINFO info = DRMINFO.getInstance();
			_webServer.InitInstance(info.IMEI, info.MACADDRESS, this);
			_webServer.StartServer(50000);
		}
	}

	private void DRM_showInfo()
	{
		int nEndTime = _webServer.GetEndTime();
		int nCountPolicy = _webServer.GetPolicyCount();
		int nPolicyType = _webServer.GetPolicyType();

		if (nPolicyType == 0x102) // 
		{
			Log.d(TAG, "policy type : period");
			if (nEndTime > 0) {
				long lTime = (long) nEndTime * 1000;
				Log.d(TAG, "time : " + Long.toString(lTime) + ", "+ Integer.toString(nEndTime));
				Date date = new Date(lTime);
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.KOREA);
				displayMessage(format.format(date) + "");
			}
		}
		if (nPolicyType == 0x104) //
		{
			if (nCountPolicy > 0) {
				Log.d(TAG, "policy type : count");
				displayMessage(" " + nCountPolicy + " 회");
			}
		}
		if (nPolicyType == (0x102 | 0x104)) //
		{
			Log.d(TAG, "period + count");
			long lTime = (long) nEndTime * 1000;
			Log.d(TAG, "time : " + Long.toString(lTime) + ", "+ Integer.toString(nEndTime));
			Date date = new Date(lTime);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.KOREA);
			if ((nEndTime > 0) && (nCountPolicy > 0))
				displayMessage(format.format(date) + "  "
						+ nCountPolicy + " ");
		}
	}

	public void displayMessage(String message){
		if(message != null){
			Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
		}
	}
	
}
